package com.zmc.lostfound.search.config;

import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.BindingBuilder;
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.core.TopicExchange;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import static com.zmc.lostfound.common.constant.RabbitMqConstant.*;

/**
 * 声明交换机与消息队列以及它们的绑定关系
 *
 * @author ZMC
 */
@Configuration
public class RabbitPostMqConfig {

    /**
     * 注册Exchange交换机: post.topic
     * 参数1: 交换机名称
     * 参数2: durable: 是否持久化(开启后将会存到硬盘中, 服务器重启也不删除, 默认false)
     * 参数3: autoDelete: 是否自动删除(当所有的与此连接的客户端都断开时, 该交换器自动删除, 默认false)
     * 参数4: arguments: 交换机的其它参数
     */
    @Bean
    public TopicExchange postTopicExchange() {
        return new TopicExchange(POST_EXCHANGE, true, false, null);
    }

    /**
     * 注册消息队列: post.save.queue
     * 参数1: 队列名称
     * 参数2: durable: 是否持久化(默认true)
     * 参数3: exclusive: 代表该队列独占(只允许有一个consumer监听, 默认false)
     * 参数4: autoDelete: 是否自动删除(没有consumer监听时, 该队列自动删除, 默认false)
     * 参数5: arguments: 队列的其它参数
     */
    @Bean
    public Queue postSaveQueue() {
        return new Queue(POST_SAVE_QUEUE, true, false, false, null);
    }

    /**
     * 注册消息队列: post.delete.queue
     * 参数1: 队列名称
     * 参数2: durable: 是否持久化(默认true)
     * 参数3: exclusive: 代表该队列独占(只允许有一个consumer监听, 默认false)
     * 参数4: autoDelete: 是否自动删除(没有consumer监听时, 该队列自动删除, 默认false)
     * 参数5: arguments: 队列的其它参数
     */
    @Bean
    public Queue postDeleteQueue() {
        return new Queue(POST_DELETE_QUEUE, true, false, false, null);
    }

    /**
     * 绑定队列saveQueue到交换机topicExchange
     */
    @Bean
    public Binding postSaveQueueBinding(@Qualifier(value = "postSaveQueue") Queue saveQueue, @Qualifier(value = "postTopicExchange") TopicExchange topicExchange) {
        return BindingBuilder
                .bind(saveQueue)
                .to(topicExchange)
                .with(POST_SAVE_KEY);
    }

    /**
     * 绑定队列deleteQueue到交换机topicExchange
     */
    @Bean
    public Binding postDeleteQueueBinding(@Qualifier(value = "postDeleteQueue") Queue deleteQueue, @Qualifier(value = "postTopicExchange") TopicExchange topicExchange) {
        return BindingBuilder
                .bind(deleteQueue)
                .to(topicExchange)
                .with(POST_DELETE_KEY);
    }

}